<template>
	<div id="app">
		<el-row>
			<el-col :span="24">
				<el-form :model="queryWhere" :inline="true">
					<el-form-item label="用户名">
						<el-input v-model="queryWhere.username"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="initTableData">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" style="float: right;" @click="addDialog()">添加用户</el-button>
					</el-form-item>
				</el-form>
			</el-col>


		</el-row>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryWhere.currentPage" :page-sizes="[5,10, 15, 20, 30]" :page-size="pageInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecord">
		</el-pagination>
		<el-table :data="userList" stripe border style="width: 100%" v-loading="loading">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" inline class="demo-table-expand" label-width="200px">
						<el-form-item label="创建时间">
							<span>{{ props.row.created }}</span>
						</el-form-item>
						<el-form-item label="修改时间">
							<span>{{ props.row.updated }}</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>

			<el-table-column label="可用状态" prop="flag">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.flag == 1?true :false" @change="userStatusChanged(scope.row)">
					</el-switch>
				</template>
			</el-table-column>

			<el-table-column prop="username" label="用户名"></el-table-column>
			<el-table-column prop="tel" label="手机号"></el-table-column>
			<el-table-column prop="file" label="头像">
				<template slot-scope="scope">
					<el-image style="width: 50px; height: 50px" :src="scope.row.file" fit="fill"></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="role.role_name" label="角色"></el-table-column>

			<el-table-column label="操作" fixed="right" align="center" width="300">
				<template slot-scope="scope">
					<!-- 修改按钮 -->
					<el-button type="primary" icon="el-icon-edit" size="small" @click="editDialog(scope)">修改
					</el-button>
					<!-- 删除按钮 -->
					<el-button type="danger" icon="el-icon-delete" size="small" @click="delDialog(scope.row.user_id)">删除
					</el-button>
					<!-- 授权按钮 -->
					<el-button type="warning" icon="el-icon-key" size="small" @click="setDialog(scope.row) ">授权
					</el-button>
				</template>

			</el-table-column>

		</el-table>
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryWhere.currentPage" :page-sizes="[5,10, 15, 20, 30]" :page-size="pageInfo.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.totalRecord">
		</el-pagination>




		<!-- 修改用户 弹出框  -->
		<el-dialog title="修改管理员信息" :visible.sync="dialogVisible" width="1024">


			<el-form :model="userInfo" label-width="100px">
				<el-form-item label-width="0">
					<el-button type="success" @click="resetUserPassword">重置用户密码</el-button>
				</el-form-item>
				<el-form-item label="用户名">
					<el-input v-model="userInfo.username" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input v-model="userInfo.password" type="password" disabled></el-input>
				</el-form-item>
				<el-form-item label="电话号码">
					<el-input v-model="userInfo.tel"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="userInfo.flag" placeholder="请选择" size="small">
						<el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="updateUser">确 定</el-button>
			</div>

		</el-dialog>

		<!-- 添加 弹出框  -->
		<el-dialog title="添加管理员信息" :visible.sync="dialogVisibleadd" width="1024">

			<el-form :model="userInfo" :inline="false" label-width="100px">
				<el-form-item label="用户名">
					<el-input v-model="userInfo.username"></el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input v-model="userInfo.password"></el-input>
				</el-form-item>
				<el-form-item label="电话号码">
					<el-input v-model="userInfo.tel"></el-input>
				</el-form-item>
				<el-form-item>
					<el-upload class="avatar-uploader" action="http://localhost:8080/api/mall/OSSFileUploadServlet"
						:show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						<!--判断data中的imgUrl是否为空，不为空则显示imgUrl-->
						<img v-if="userInfo.file" :src="userInfo.file" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleadd = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</div>

		</el-dialog>
		<!-- 授权 弹出框  -->
		<el-dialog title="授权用户" :visible.sync="dialogVisibleset" width="1024">

			<el-form :model="roleForm" :inline="true" label-width="100px">
				<el-select v-model="roleForm.selectRoleId" placeholder="请选择" size="small">
					<el-option v-for="item in roleList" :key="item.role_id" :value="item.role_id"
						:label="item.role_name">
					</el-option>
				</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleset = false">取 消</el-button>
				<el-button type="primary" @click="setUser">确 定</el-button>
			</div>
		</el-dialog>

	</div>
</template>

<script>
	export default {
		name: 'User',
		created: function() {
			this.access_token = window.sessionStorage.getItem("token");
		},
		mounted: function() {
			this.initTableData();
			//角色下拉框mounted的时候查出来
			this.getRoleList()
		},
		computed: {},
		methods: {
			handleSizeChange: function(pageSize) {
				//alert("修改了每页显示的记录数",val);
				//console.log("修改了每页显示的记录数",val)
				this.queryWhere.pageSize = pageSize;
				this.initTableData(); //重新查数据库。。
			},
			//上传图片相关回调
			handleAvatarSuccess: function(res, file) {
				console.log("res值：", res);
				if (res.code == 0) {
					this.userInfo.file = res.data;
				} else {
					_this.$notify({
						title: '提示',
						message: res.msg,
						duration: 2000
					});
				}
			},
			beforeAvatarUpload: function(file) {
				//文件上传前对文件的大小和类型做检查
				const isJPG = file.type.indexOf('image') >= 0 ? true : false;
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('只能上传图片!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			//重置用户密码
			resetUserPassword() {
				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=resetUserPassword&access_token=" + this.access_token;

				this.$http.get(url, {
					params: {
						user_id: this.userInfo.user_id
					}
				}).then(function(response) {
					console.log("服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.$message.success(response.data.msg)
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});

				});
			},
			userStatusChanged: function(userInfo) {

				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=updateUserStateExChange&access_token=" + this.access_token;

				this.$http.get(url, {
					params: {
						flag: userInfo.flag,
						user_id: userInfo.user_id
					}
				}).then(function(response) {
					console.log("服务端返回的数据为:", response);
					if (response.data.code == 0) {
						if (userInfo.flag != 0) {
							userInfo.flag = 0;
						} else {
							userInfo.flag = 1;
						}
						return _this.$message.success("更新会员状态成功！")
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});

				})

			},
			//删除用户 真的删除
			delDialog: async function(userId) {

				//弹框询问是否删除
				const confirmResult = await this.$confirm('是否删除该角色', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(function(error) {
					console.log(error);
				})

				if (confirmResult != 'confirm') {
					return this.$message.info('已取消删除')
				}

				//发生请求删除用户信息
				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=deleteUserById&access_token=" + this.access_token;
				await this.$http.get(url, {
					params: {
						userId: userId
					}
				}).then(function(response) {
					console.log("address服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.$message({
							message: response.data.msg,
							type: 'success'
						});
					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})
				_this.loading = true;
				this.initTableData(); //重新查数据库。。
			},


			updateUser: function() {
				let _this = this;
				console.log("传递给后端的数据为:", this.userInfo)
				let url = "/api/mall/UserServlet2.do?method=updateUserById&access_token=" + this.access_token;
				this.$http.get(url, {
					params: this.userInfo
				}).
				then(function(response) {
					console.log("服务端返回的结果为:", response);
					if (response.data.code == 0) {
						//关闭Dialog
						_this.dialogVisible = false;
						//重新刷新表格数据
						//_this.initTableData();
						_this.$notify({
							title: '提示',
							message: "修改成功",
							duration: 2000
						});
						//把修改后的数据更新到表格中
						for (let attr in _this.userInfo) {
							_this.currentEditUserInfo[attr] = _this.userInfo[attr]
						}
					}else{
						_this.$notify({
							title: '提示',
							message: response.data.msg,
							duration: 2000
						});
					}
				}).
				catch(function(error) {
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})
			},

			editDialog: function(scope) { //点击修改按钮调用的函数
				//发生请求修改用户信息
				this.currentEditUserInfo = scope.row;
				//把当前修改的书刊赋给currentEditUserInfo,
				//目的是在修改成功时，把userInfo中的数据替换currentEditBookInf
				this.dialogVisible = true; //显示弹出框
				console.log('scope.row', scope.row)
				for (let attr in this.userInfo) {

					this.userInfo[attr] = scope.row[attr]
				}

			},
			//增加用户
			addDialog: function() {
				for (let key in this.userInfo) {
					this.userInfo[key] = '';
				}
				this.dialogVisibleadd = true; //显示弹出框
			},
			addUser: function() {
				let _this = this;
				console.log("传递给后端的数据为:", this.userInfo)
				let url = "/api/mall/UserServlet2.do?method=saveUser&access_token=" + this.access_token;
				this.$http.get(url, {
					params: this.userInfo
				}).
				then(function(response) {
					console.log("服务端返回的结果为:", response);
					if (response.data.code == 0) {
						_this.$message({
							message: response.data.msg,
							type: 'success'
						});
					} else {
						_this.$message(response.data.msg)
					}
				}).catch(function(error) {
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})

				_this.dialogVisibleadd = false

				_this.loading = true;
				this.initTableData();
			},


			//授权用户
			setUser: function() {
				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=assignRole";

				console.log(111111111111111111111111111);
				this.$http.get(url, {
					params: {
						role_id: _this.roleForm.selectRoleId,
						user_id: _this.selectUserId
					}
				}).then(function(response) {
					console.log("address服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.dialogVisibleset = false;
						_this.$notify({
							title: '提示',
							message: response.data.msg,
							duration: 2000
						});

						//修改成功后偶 session中的权限id也要改变
						console.log(_this.roleForm.selectRoleId, '!!!11111111111111')
						window.sessionStorage.setItem("role_id", _this.roleForm.selectRoleId);
					} else {
						_this.$message(response.data.msg)
					}
				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})
				_this.loading = true;
				this.initTableData(); //重新查数据库。。

			},
			//查询用户的角色
			getRoleList: function() {
				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=getRoleList&access_token=" + this.access_token;
				console.log(222222222222);
				this.$http.get(url).then(function(response) {
					console.log("address服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.roleList = response.data.data;
					} else {
						_this.$message(response.data.msg)
					}
				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});
				})
			},
			//查询角色下拉框数据
			setDialog: function(user) {
				this.dialogVisibleset = true; //显示弹出框
				this.selectUserId = user.user_id;

			},
			initTableData: function() {
				let _this = this;
				let url = "/api/mall/UserServlet2.do?method=query&access_token=" + this.access_token;

				this.$http.get(url, {
					params: _this.queryWhere
				}).then(function(response) {
					console.log("服务端返回的数据为:", response);
					if (response.data.code == 0) {
						_this.queryWhere.currentPage = response.data.data.currentPage;
						_this.pageInfo.totalPage = response.data.data.totalPage;
						_this.pageInfo.totalRecord = response.data.data.totalRecord;
						_this.pageInfo.pageSize = response.data.data.pageSize;
						_this.userList = response.data.data.data;

					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});

				})
				_this.loading = false;

			},

			handleCurrentChange: function(curPage) {
				this.queryWhere.currentPage = curPage; //当页页
				this.initTableData(); //重新查数据库。。
			}
		},
		data: function() {
			return {
				loading: true,
				//记录token
				access_token: "",
				dialogVisible: false, //修改
				dialogVisibleadd: false, //增加
				dialogVisibleset: false, //授权
				roleList: [], //角色集合
				roleForm: {
					selectRoleId: '请选择用户角色',
				},
				selectUserId: "",

				currentEditUserInfo: {}, //用于存储管理员点击修改时的用户信息
				userInfo: {
					user_id: "",
					username: "",
					password: "",
					tel: "",
					file: "",
					flag: "",
					created: "",
					updated: ""

				},
				queryWhere: {
					username: "",
					currentPage: 1,
					pageSize: 5
				},
				pageInfo: {
					pageSize: 5,
					totalPage: 0,
					totalRecord: 0
				},

				userList: [],
				options: [{
						value: 1,
						label: "可用"

					},
					{
						value: 0,
						label: "不可用"

					}
				],
				value: ""
			}
		},
	}
</script>

<style>
	.el-col {
		border-radius: 4px;
	}

	.bg-purple-dark {
		background: #99a9bf;
	}

	.bg-purple {
		background: #d3dce6;
	}

	.bg-purple-light {
		background: #e5e9f2;
	}

	.grid-content {
		border-radius: 4px;
		min-height: 36px;
	}


	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
